package com.wwlwxg.spring_security.controller;


import com.wwlwxg.spring_security.config.Pet;
import com.wwlwxg.spring_security.entity.Users;
import com.wwlwxg.spring_security.exception.UserTooManyException;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PreFilter;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/test")
public class HelloController {

  @RequestMapping("/hello")
  public String test1() {
    return "123";
  }

  @RequestMapping("/index")
  public String index() {
    return "index";
  }

  @RequestMapping("/update")
  @Secured("ROLE_sale")
  public String update() {
    return "hello update";
  }

  @RequestMapping("/t1")
  @PreAuthorize("hasAnyAuthority('admin')")
  public String t1() {
    return "t1";
  }

  // 方法执行完毕之后，再去进行权限校验
  @RequestMapping("/t2")
  @PostAuthorize("hasAnyAuthority('admin')")
  public String t2() {
    return "t2";
  }

  // 只会返回users的username为admin的一条json数据， @PreFilter是对参数进行过滤
  @RequestMapping("/t3")
  @PreAuthorize("hasRole('ROLE_sale')")
  @PostFilter("filterObject.username == 'admin'")
  public List<Users> t3() {
    List<Users> list = new ArrayList<>();
    list.add(new Users(1, "admin", "pass1"));
    list.add(new Users(2, "user2", "pass2"));
    list.add(new Users(3, "user3", "pass3"));
    return list;
  }

  @RequestMapping("/t4")
  @PreAuthorize("hasRole('ROLE_sale')")
  public Pet t4() {
    Pet pet = new Pet();
    pet.setId(1);
    pet.setName("aa");
    if(pet.getName().equals("aa")) {
      throw new UserTooManyException("aaa");
    }
    return pet;
  }
}
